<template>
  <!-- 完工单详情 -->
  <div
    class="OrderDetail"
    v-if="info"
  >
    <div class="g-con">
      <div class="flexec">
        <el-button
          v-if="type === 'add'"
          type="primary"
          @click="handleSave"
        >
          {{ t('save') }}
        </el-button>
        <el-button @click="handleExport"> {{ t('exportPDF') }} </el-button>
        <!-- <el-button> {{ t('print') }} </el-button> -->
      </div>

      <div class="bg shipinfo mt-2">
        <div class="grid">
          <div class="img">
            <img
              :src="info.shcwShippingVo.picture"
              alt=""
            />
          </div>
          <div class="attr">
            <div class="item">
              <span>{{ t('invitationQuotation.attr1') }}:</span>
              <span>{{ info.dockShowInfoVo.orderNo }}</span>
            </div>
            <div class="item">
              <span>{{ t('invitationQuotation.attr2') }}:</span>
              <span>{{ info.dockShowInfoVo.dockOrderName }}</span>
            </div>
            <div
              class="item"
              v-for="({ label, key, unit, dict }, index) in attrList"
              :key="index"
            >
              <span>{{ label }}:</span>
              <span v-if="dict">{{ getDictLabel(dict, info.shcwShippingVo[key]) }}{{ unit }}</span>
              <span v-else>{{ info.shcwShippingVo[key] }}{{ unit }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="bg list mt-5">
        <div
          class="group flexsc"
          v-if="type === 'add'"
        >
          <!-- 系统维修项目 -->
          <!-- <el-button
            type="primary"
            @click="handleAdd('0')"
            :disabled="setBtnDiasbled('0')"
          >
            +{{ t(`dockRepair.btn1`) }}
          </el-button> -->

          <!-- 自定义维修项目 -->
          <el-button
            type="primary"
            @click="handleAdd('2')"
            :disabled="setBtnDiasbled('2')"
          >
            +{{ t(`dockRepair.btn2`) }}
          </el-button>

          <!-- 说明 -->
          <el-button
            type="primary"
            @click="handleAdd('1')"
            :disabled="setBtnDiasbled('1')"
          >
            +{{ t(`dockRepair.btn3`) }}
          </el-button>

          <!-- 附加项 -->
          <!-- <el-button
            type="primary"
            @click="handleAdd('3')"
            :disabled="setBtnDiasbled('3')"
          >
            +{{ t(`dockRepair.btn4`) }}
          </el-button> -->

          <el-button
            type="primary"
            @click="handleAddItemPipeline()"
            :disabled="setBtnDiasbled('3')"
          >
            +{{ t(`dockRepair.btn9`) }}
          </el-button>
          <el-button
            type="primary"
            :disabled="setBtnDiasbled('3')"
            @click="handleAddItemValve()"
          >
            +{{ t(`dockRepair.btn10`) }}
          </el-button>
          <el-button
            type="primary"
            :disabled="setBtnDiasbled('3')"
            @click="handleAddItemSteelStructure()"
          >
            +{{ t(`dockRepair.btn11`) }}
          </el-button>

          <!-- 耗材 -->
          <el-button
            type="primary"
            @click="handleAdd('4')"
            :disabled="setBtnDiasbled('4')"
          >
            +{{ t(`dockRepair.btn8`) }}
          </el-button>
        </div>

        <div :class="['table', 'mt-2', locale]">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table-v2
                :columns="columns"
                :data="tableData"
                :width="width"
                :height="height"
                :row-class="setRowClass"
                fixed
              />
            </template>
          </el-auto-resizer>
        </div>
      </div>

      <div class="bg mt-3">
        <div class="tit">{{ t('attachments') }}</div>
        <div
          v-if="type === 'add'"
          class="con mt-2"
        >
          <Uploads
            ref="UploadsRef"
            @change="fileChange"
            :tip="t('Uploads.t2')"
          />
        </div>

        <div
          class="con mt-2"
          v-if="type === 'detail'"
        >
          <div
            v-for="(item, index) in info.urlList"
            :key="index"
          >
            <a
              :href="item"
              target="_blank"
            >
              {{ item.file_name }}
            </a>
          </div>
        </div>
      </div>
    </div>

    <!-- 维修选项 -->
    <ProjectType
      v-if="dialogProjectType"
      :samallId="checkedRow.projectId"
      :projectParent="checkedRow.projectParent"
      :visible="dialogProjectType"
      @close="dialogProjectType = false"
      @confirm="itemTypeConfirm"
    />

    <!-- 维修附加项 -->
    <AdditionItem
      v-if="dialogAdditionItem"
      :visible="dialogAdditionItem"
      @close="dialogAdditionItem = false"
      @confirm="additionItemConfirm"
    />

    <!-- 管路 -->
    <Pipeline
      v-if="pipelineDialog"
      v-model="pipelineDialog"
      :checkedRow="checkedRow"
      :shipType="info.shcwShippingVo.shippingType"
      :isFinishOrder="true"
      @getData="getDetail(false)"
    />

    <!-- 阀门 -->
    <Valve
      v-if="valveDialog"
      v-model="valveDialog"
      :checkedRow="checkedRow"
      :shipType="info.shcwShippingVo.shippingType"
      :isFinishOrder="true"
      @getData="getDetail(false)"
    />

    <!-- 钢结构 -->
    <SteelStructure
      v-if="steelStructureDialog"
      v-model="steelStructureDialog"
      :checkedRow="checkedRow"
      :isFinishOrder="true"
      @getData="getDetail(false)"
    />
  </div>
</template>

<script setup lang="jsx">
import { ref, reactive, onBeforeMount, unref, watch, nextTick, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getFinishOrderDetailApi, saveFinishOrderApi, updateShcwFinishOrderDetailApi, deleteDetailPhysicalApi, exportFinishOrderApi } from '@/service/dockOrder'
import { useI18n } from 'vue-i18n'
import { setItemNumber, download } from '@/utils/index'
import { uploads } from '@/service/common'
import { debounce } from 'lodash'

import Decimal from 'decimal.js'

import ProjectType from '@/views/dockRepair/ProjectType.vue' // 维修选项
import AdditionItem from '@/views/dockRepair/AdditionItem.vue' // 维修附加项
import Pipeline from '@/views/dockRepair/Pipeline.vue' // 管路
import Valve from '@/views/dockRepair/Valve.vue' // 阀门
import SteelStructure from '@/views/dockRepair/SteelStructure.vue' // 钢结构
import { amountFormat } from '@/utils/index'
import useLogin from '@/stores/login'
import Uploads from '@/components/Uploads.vue'

import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()
const storeLogin = useLogin()

const router = useRouter()
const route = useRoute()
const { t, locale } = useI18n()

const id = route.query.id
const type = ref('add')

watch(locale, (n) => {
  init()
})
// 是否生产主管或者生产经理
const isProduction = computed(() => {
  return storeLogin?.userInfo?.roleNameEn === 'SRM' || storeLogin?.userInfo?.roleNameEn === 'Production Manager'
})
onBeforeMount(() => {
  init()
})

// 导出
const handleExport = () => {
  exportFinishOrderApi({ id }).then((res) => {
    download(res)
  })
}

// 保存报价单
const handleSave = async () => {
  const params = {
    id
  }

  params.urlList = await handleUpload()

  saveFinishOrderApi(params).then(({ msg }) => {
    ElMessage.success(msg)
    getDetail()
  })
}

// 维修选项(项目类型)
const dialogProjectType = ref(false)
// 维修选项 确认
const itemTypeConfirm = (value) => {
  // console.log(value)
  const { repairProjectId, parentId, projectName, projectNameCn, projectNameEn, unit, unitCn, unitEn } = value

  const row = tableData.value[editIndex]

  row.projectId = repairProjectId
  row.projectParent = parentId
  row.projectName = projectName
  row.projectNameCn = projectNameCn
  row.projectNameEn = projectNameEn
  row.unit = unit
  row.unitCn = unitCn
  row.unitEn = unitEn
}

// 维修附加项
const dialogAdditionItem = ref(false)
const additionItemConfirm = (value) => {
  const { id, projectName, projectCnName, projectEnName, projectUnit, projectCnUnit, projectEnUnit } = value

  const row = tableData.value[editIndex]

  row.additionalId = id
  row.projectId = null
  row.projectParent = checkedRow.value.projectParent
  row.projectName = projectName
  row.projectNameCn = projectCnName
  row.projectNameEn = projectEnName
  row.unit = projectUnit
  row.unitCn = projectCnUnit
  row.unitEn = projectEnUnit
}

// 正在编辑的 index
let editIndex = null

// 勾选的 行
let checkedRow = ref(null)

// 按钮禁用
const setBtnDiasbled = (dataType) => {
  const _data = unref(tableData.value)
  let flag = false
  if (checkedRow.value === null) {
    flag = true
  } else {
    // 勾选的行级别不为2的  只能点击'说明'
    if (dataType !== '1' && checkedRow.value.projectLevel !== 2) {
      flag = true
    }

    // 自定义
    if (dataType === '2' && ![0, 1].includes(checkedRow.value.projectLevel)) {
      flag = false
    }

    // 附加项
    if (dataType === '3') {
      flag = false
    }
  }
  return flag || _data.some((d) => !d.isSave)
}

// 行 class
const setRowClass = ({ columns, rowData, rowIndex }) => {
  // console.log(columns, rowData, rowIndex, '---')
  let str = ''

  if (rowData.projectLevel !== null) {
    str += ` projectLevel-${rowData.projectLevel}`
  }

  if (!rowData.isSave) {
    str += ' no-save'
  }

  return str
}

// 复选框 组件
const SelectionCell = ({ value, intermediate = false, onChange }) => {
  return (
    <ElCheckbox
      onChange={onChange}
      modelValue={value}
      indeterminate={intermediate}
    />
  )
}
// 获取列
const getColumns = () => {
  const setRef = (el) => {
    if (el) {
      el.focus?.()
    }
  }
  const setEditingClassName = (flag) => {
    return { 'table-v2-inline-editing-trigger': flag }
  }
  const editingClassName = { 'table-v2-inline-editing-trigger': type.value === 'add' }
  // 保存
  const handleRowSave = debounce(
    (rowData) => {
      const params = { ...rowData }
      if (rowData.dataType === '2') {
        params.projectNameCn = params.projectNameEn = params.projectName
        params.unitCn = params.unitEn = params.unit
      }
      if (rowData.dataType === '1') {
        params.unitCn = params.unitEn = params.unit
      }

      // 无id时 为新增
      if (!params.id) {
        params.previousId = checkedRow.value.id // 上一个明细id(勾选的id)
      }

      updateShcwFinishOrderDetailApi({
        finishOrderId: id, // 完工单id
        ...params
      }).then(({ data }) => {
        rowData.isSave = true
        rowData.editingKey = null
        checkedRow.value = null
        editIndex = null
        rowData.id = data
        ElMessage.success(t('saveSuccess'))

        const _data = unref(tableData.value)
        setItemNumber(_data)
      })
    },
    500,
    {
      leading: true, // 延长开始后调用
      trailing: false // 延长结束前调用
    }
  )

  // 回车保存
  const handleEnterSave = (e, rowData) => {
    if (['Enter', 'NumpadEnter'].includes(e.code)) {
      handleRowSave(rowData)
    }
  }
  // 计算折扣
  const compute = (rowData) => {
    const { requireCount, price, discount } = rowData
    // activeItem.amount = requireCount * price * (1 - discount * 0.01)
    rowData.amount = Number(
      Decimal(requireCount || 0)
        .mul(Decimal(price || 0))
        .mul(Decimal(1).sub(Decimal(discount || 0).mul(0.01)))
    )
  }
  columns.value = [
    {
      key: 'selection',
      width: 50,
      fixed: 'left',
      align: 'center',
      cellRenderer: ({ rowData }) => {
        const _data = unref(tableData.value)
        const onChange = (value) => {
          _data.forEach((row) => (row.checked = false))
          rowData.checked = value
          checkedRow.value = value ? rowData : null
        }

        if (_data.every((d) => d.isSave)) {
          return (
            <SelectionCell
              value={rowData.checked}
              onChange={onChange}
            />
          )
        }
      }
    },
    {
      title: t('dockRepair.coltit1'), // 项目编号
      key: 'itemNumber',
      dataKey: 'itemNumber',
      width: 100,
      class: 'itemNumber',
      align: 'center'
    },
    {
      title: t('dockRepair.coltit2'), // 项目类型
      key: 'projectName',
      dataKey: 'projectName',
      width: isProduction.value ? 590 : 450,
      cellRenderer: ({ rowData, rowIndex }) => {
        const isEdit = ['1', '2', '3'].includes(rowData.dataType)

        if (rowData.editingKey === 'projectName') {
          if (isEdit) {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.projectName}
                placeholder=" "
                maxlength={100}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'projectName'
        }

        return (
          <div
            class={setEditingClassName(isEdit)}
            onClick={onEnterEditMode}
          >
            {rowData.projectName}
          </div>
        )
      }
    },
    {
      title: t('dockRepair.coltit3'), // 项目类型说明
      key: 'projectContent',
      dataKey: 'projectContent',
      width: 280,
      cellRenderer: ({ rowData, rowIndex }) => {
        const isEdit = ['0', '2', '3', '4'].includes(rowData.dataType)

        if (rowData.editingKey === 'projectContent') {
          if (isEdit) {
            if (['0', '2', '3'].includes(rowData.dataType)) {
              return (
                <el-input
                  ref={setRef}
                  v-model={rowData.projectContent}
                  placeholder=" "
                  maxlength={100}
                  onBlur={() => {
                    handleRowSave(rowData)
                  }}
                  onKeyup={(e) => handleEnterSave(e, rowData)}
                />
              )
            }

            if (['4'].includes(rowData.dataType)) {
              const compute = () => {
                if (rowData.projectContent1 && rowData.projectContent2 && rowData.projectContent3 && rowData.projectContent4) {
                  const { projectContent1, projectContent2, projectContent3, projectContent4 } = rowData
                  rowData.projectContent = JSON.stringify({
                    projectContent1,
                    projectContent2,
                    projectContent3,
                    projectContent4
                  })
                  rowData.requireCount = (Decimal(projectContent1) * Decimal(projectContent2) * Decimal(projectContent3) * Decimal(projectContent4)).toFixed(0)

                  handleRowSave(rowData)
                }
              }

              return (
                <>
                  <el-input-number
                    min={0}
                    controls={false}
                    v-model={rowData.projectContent1}
                    placeholder={t('userCenter.p1')}
                    onBlur={() => {
                      compute()
                    }}
                    style="width: 90px"
                  />
                  <el-input-number
                    min={0}
                    controls={false}
                    v-model={rowData.projectContent2}
                    placeholder={t('userCenter.p2')}
                    onBlur={() => {
                      compute()
                    }}
                    style="width: 90px"
                  />
                  <el-input-number
                    min={0}
                    controls={false}
                    v-model={rowData.projectContent3}
                    placeholder={t('userCenter.p3')}
                    onBlur={() => {
                      compute()
                    }}
                    style="width: 90px"
                  />
                  <el-input-number
                    min={0}
                    controls={false}
                    v-model={rowData.projectContent4}
                    placeholder={t('userCenter.p4')}
                    onBlur={() => {
                      compute()
                    }}
                    style="width: 90px"
                  />
                  <div>{t('userCenter.u1')}(mm)</div>
                </>
              )
            }
          }
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'projectContent'
        }

        if (['4'].includes(rowData.dataType)) {
          const { projectContent1, projectContent2, projectContent3, projectContent4 } = JSON.parse(rowData.projectContent || '{}')
          return (
            <div
              class={setEditingClassName(isEdit)}
              onClick={onEnterEditMode}
            >
              {`${t('userCenter.projectContent1')}${projectContent1 || 0}mm,${t('userCenter.projectContent2')}${projectContent2 || 0}mm,${t('userCenter.projectContent3')}${projectContent3 || 0}mm,${t('userCenter.projectContent4')}${projectContent4 || 0}`}
            </div>
          )
        }

        return (
          <div
            class={setEditingClassName(isEdit)}
            onClick={onEnterEditMode}
          >
            {rowData.projectContent}
          </div>
        )
      }
    },
    {
      title: t('dockRepair.coltit4'), // 单位
      key: 'unit',
      dataKey: 'unit',
      width: 98,
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        const isEdit = ['2', '3'].includes(rowData.dataType) && ![0, 1].includes(rowData.projectLevel)

        if (rowData.editingKey === 'unit') {
          if (isEdit) {
            return (
              <el-input
                ref={setRef}
                v-model={rowData.unit}
                placeholder=" "
                maxlength={100}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'unit'
        }

        return (
          <div
            class={setEditingClassName(isEdit)}
            onClick={onEnterEditMode}
          >
            {rowData.unit}
          </div>
        )
      }
    },
    {
      title: t('dockRepair.coltit5'), // 数量
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 95,
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        const isEdit = ['0', '2', '3'].includes(rowData.dataType) && ![0, 1].includes(rowData.projectLevel)

        if (rowData.editingKey === 'requireCount') {
          if (isEdit) {
            return (
              <el-input-number
                ref={setRef}
                v-model={rowData.requireCount}
                min={0}
                controls={false}
                onBlur={() => {
                  handleRowSave(rowData)
                }}
                onKeyup={(e) => handleEnterSave(e, rowData)}
              />
            )
          }
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'requireCount'
        }

        return (
          <div
            class={setEditingClassName(isEdit)}
            onClick={onEnterEditMode}
          >
            {rowData.requireCount}
          </div>
        )
      }
    },
    {
      title: t('userCenter.price'), //
      key: 'price',
      dataKey: 'price',
      width: 110,
      align: 'center',
      hidden: isProduction.value,
      cellRenderer: ({ rowData, rowIndex }) => {
        if ([0, 1].includes(rowData.projectLevel)) return

        watch(
          () => rowData.price,
          (newVal) => {
            // if (!newVal) return
            compute(rowData)
          }
        )

        if (rowData.editingKey === 'price') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.price}
              controls={false}
              min={0}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'price'
          }
        }

        return (
          <div class={editingClassName} onClick={onEnterEditMode}>
            {amountFormat(rowData.price)}
          </div>
        )
      }
    },
    {
      title: t('userCenter.discount'), //
      key: 'discount',
      dataKey: 'discount',
      width: 110,
      align: 'center',
      hidden: isProduction.value,
      cellRenderer: ({ rowData, rowIndex }) => {
        if ([0, 1].includes(rowData.projectLevel)) return

        watch(
          () => rowData.discount,
          (newVal) => {
            compute(rowData)
          }
        )

        if (rowData.editingKey === 'discount') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.discount}
              controls={false}
              min={0}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          if (type.value === 'add') {
            rowData.editingKey = 'discount'
          }
        }

        return (
          <div class={editingClassName} onClick={onEnterEditMode}>
            {rowData.discount !== null ? `${rowData.discount}%` : ''}
          </div>
        )
      }
    },
  ]

  // 0未完成 1已完成
  if (type.value === 'add') {
    columns.value.push({
      title: t('dockRepair.coltit6'), // 操作
      width: 120,
      fixed: 'right',
      align: 'center',
      cellRenderer: ({ rowData, rowIndex }) => {
        const _data = unref(tableData.value)

        // 删除
        const handleRowDelete = (value) => {
          if (!rowData.id) {
            _data.splice(rowIndex, 1)
            checkedRow.value = null
            editIndex = null
            setItemNumber(_data)
            return
          }
          // console.log(value)
          deleteDetailPhysicalApi({
            id: rowData.id
          }).then(({ msg }) => {
            ElMessage.success(msg)
            // _data.splice(rowIndex, 1)
            // setItemNumber(_data)
            checkedRow.value = null
            editIndex = null
            getDetail()
          })
        }
        return (
          <>
            <el-popconfirm
              title={rowData.dataType === '1' ? t('popconfirm_del') : t('dockRepair.step2page.popconfirm_del')}
              width={260}
              v-slots={{
                reference: () => (
                  <img
                    src={new URL('@/assets/img/icon_shanchu.png', import.meta.url)}
                    height="22"
                  />
                )
              }}
              onConfirm={handleRowDelete}
            ></el-popconfirm>
          </>
        )
      }
    })
  }
}

// 表格 列
const columns = ref([])

// 回显(表格数据)
const tableData = ref([])

// 在选中行下面插入一行
const handleAdd = (dataType) => {
  const _data = unref(tableData.value)
  const index = _data.findIndex((row) => row.checked)
  if (index === -1) {
    return
  }
  _data.forEach((row) => (row.checked = false))

  let obj = {
    isSave: false,
    projectLevel: 2,
    dataType
  }

  if (dataType === '2') {
    obj.projectParent = checkedRow.value.projectParent
    obj.projectLevel = checkedRow.value.projectLevel
  }

  if (dataType === '1') {
    obj.projectName = '说明' // 固定为 '说明'
    obj.projectNameCn = '说明'
    obj.projectNameEn = 'explain'
    obj.projectLevel = checkedRow.value.projectLevel
    obj.projectParent = checkedRow.value.projectParent
    obj.projectId = null
  }

  if (dataType === '4') {
    obj.projectParent = checkedRow.value.projectParent
    obj.projectName = '钢板' // 固定为 '钢板'
    obj.projectNameCn = '钢板'
    obj.projectNameEn = 'steel plate'
    obj.unit = 'KG'
    obj.unitCn = 'KG'
    obj.unitEn = 'KG'
  }

  _data.splice(index + 1, 0, obj)
  setItemNumber(_data)
}

// 船舶属性
const attrList = ref()
const setAttrList = () => {
  attrList.value = [
    { label: t('shipping.l1'), key: 'shippingName' },
    { label: t('shipping.l2'), key: 'shippingNo' },
    { label: t('shipping.l3'), key: 'shippingType', dict: 'ships_type' },
    // { label: t('shipping.l4'), key: 'portRegistry' },
    { label: t('shipping.l5'), key: 'nationality' },
    { label: t('shipping.l6'), key: 'classificationSociety', dict: 'classification_society' },
    { label: t('shipping.l7'), key: 'shipowner' },
    { label: t('shipping.l8'), key: 'shipManagement' },
    { label: t('shipping.l9'), key: 'constructionPlant' },
    { label: t('shipping.l10'), key: 'yearOfConstruction' },
    { label: t('shipping.l11'), key: 'deadweightTon', unit: 'MT' },
    { label: t('shipping.l12'), key: 'totalLength', unit: 'm' },
    // { label: t('shipping.l13'), key: 'lengthBetweenPerpendiculars', unit: 'm' },
    { label: t('shipping.l14'), key: 'moldedDepth', unit: 'm' },
    { label: t('shipping.l15'), key: 'model', unit: 'm' },
    // { label: t('shipping.l16'), key: 'draught', unit: 'm' },
    // { label: t('shipping.l17'), key: 'lightTon', unit: 'MT' },
    { label: t('shipping.l18'), key: 'grossTon' },
    // { label: t('shipping.l19'), key: 'electricalSystem', dict: 'electrical_system' },
    { label: t('shipping.l20'), key: 'host' }
  ]
}

// 详情
const info = ref(null)
const getDetail = async () => {
  await getFinishOrderDetailApi(id).then(({ data }) => {
    info.value = data

    const { finishOrderDetailList, urlList, finishStatus } = data

    // finishStatus 0未完成 1已完成
    const obj = {
      0: 'add',
      1: 'detail'
    }
    type.value = obj[finishStatus]

    if (urlList) {
      fileList.value = urlList.map((item) => {
        return {
          name: item.file_name,
          url: item.url
        }
      })
    }

    if (type.value === 'add') {
      nextTick(() => {
        UploadsRef.value.setFileList(fileList.value)
      })
    }

    if (finishOrderDetailList) {
      finishOrderDetailList.forEach((item) => {
        item.isSave = true
      })
      tableData.value = finishOrderDetailList
      setItemNumber(finishOrderDetailList)
    }
  })
}

// 管路
const pipelineDialog = ref(false)
const handleAddItemPipeline = () => {
  pipelineDialog.value = true
}

// 阀门
const valveDialog = ref(false)
const handleAddItemValve = () => {
  valveDialog.value = true
}

// 钢结构
const steelStructureDialog = ref(false)
const handleAddItemSteelStructure = () => {
  steelStructureDialog.value = true
}

// 文件列表
const fileList = ref([])
const fileChange = (val) => {
  fileList.value = val
}
const UploadsRef = ref(null)
const handleUpload = () => {
  return new Promise((resolve, reject) => {
    const newList = fileList.value.filter((item) => item.raw)
    const oldList = fileList.value
      .filter((item) => !item.raw)
      .map((item) => {
        return {
          url: item.url,
          name: item.name
        }
      })


    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls, fileNames }) => {
        const newUrls = urls.split(',')
        fileList.value = newUrls.map((newUrl, newUrlIndex) => {
          return {
            name: fileNames.split(',')[newUrlIndex],
            url: newUrl
          }
        })
        UploadsRef.value.setFileList(fileList.value)
        resolve([
          ...oldList,
          ...newUrls.map((url, index) => {
            return {
              url,
              name: fileNames.split(',')[index]
            }
          })
        ])
      })
    } else {
      resolve(oldList)
    }
  })
}

//
const init = async () => {
  setAttrList()
  getDictData('ships_type')
  getDictData('classification_society')
  getDictData('electrical_system')
  await getDetail()
  getColumns()
}
</script>

<style scoped lang="scss">
.OrderDetail {
  background: #f5f5f5;
  padding: 30px 0;
  margin-bottom: -76px;

  .el-button {
    min-width: 140px;
  }

  .bg {
    background: #fff;
    padding: 30px;

    > .tit {
      border-bottom: 2px solid #252628;
      font-weight: bold;
      padding: 10px 0;
    }
  }

  .shipinfo {
    .grid {
      display: grid;
      grid-template-columns: 240px auto;
      gap: 40px;
    }
    .img {
      img {
        width: 100%;
        position: relative;
        z-index: 9;
      }
    }
    .attr {
      display: grid;
      grid-template-columns: repeat(2, calc(50% - 10px));
      gap: 20px;
      position: relative;
      z-index: 3;
      .item {
        span {
          font-size: 12px;
          &:first-of-type {
            color: #9d9fa5;
            margin-right: 5px;
            display: inline-block;
            width: 100px;
          }
        }
        span.blue {
          color: #3376e5;
        }
        span.yellow {
          color: #e5a833;
        }
        span.red {
          color: #ca2a02;
        }

        &:nth-of-type(1),
        &:nth-of-type(2) {
          margin-bottom: 10px;
          span {
            font-size: 14px;
            color: #252628;
          }
        }
      }
    }
  }

  .list {
    .table {
      border-top: 2px solid #252628;
      height: 700px;

      :deep(.table-v2-inline-editing-trigger) {
        border: 1px transparent dotted;
        padding: 4px;
        min-height: 26px;
        min-width: 100%;
        cursor: text;
        border-radius: 3px;
      }

      :deep(.table-v2-inline-editing-trigger:hover) {
        border-color: var(--el-color-primary);
      }

      :deep(.el-table-v2__header-cell) {
        background: #f0f3f8;
        color: #252628;
      }
      :deep(.no-save) {
        background: #f9ecd9;
      }
      :deep(.projectLevel-0) {
        background: #f7f9fb;
      }

      :deep(.projectLevel-0),
      :deep(.projectLevel-1),
      :deep(.projectLevel-2) {
        .itemNumber {
          justify-content: center;
        }
      }
      :deep(.projectLevel-3),
      :deep(.projectLevel-4) {
        .itemNumber {
          justify-content: right;
        }
      }

      // &.en {
        :deep(.el-table-v2__header-cell) {
          font-family: 'Sitka Display Semibold';
          * {
            font-size: 17px;
          }
        }

        :deep(.projectLevel-0) {
          font-family: 'Amasis MT Pro Medium';
          * {
            font-size: 17px;
            font-weight: bold;
          }
        }
        :deep(.projectLevel-1) {
          font-family: '等线';
          * {
            font-size: 16px;
            font-weight: bold;
          }
        }

        :deep(.projectLevel-2, .projectLevel-3, .projectLevel-4) {
          font-family: 'Abadi';
          * {
            font-size: 15px;
          }
        }
      // }
    }
  }
}
</style>
